package com.icedevcloud.common.core.api;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Optional;

/**
 * <p>
 * 通用返回R
 * </p>
 *
 * @author XiaoBingBy
 * @since 2023-08-12
 */
@NoArgsConstructor
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1;

    /**
     * 成功
     */
    public static final int SUCCESS = ErrorCodeEnum.SUCCESS.getCode();

    /**
     * 失败
     */
    public static final int FAILED = ErrorCodeEnum.FAILED.getCode();

    /**
     * 业务错误码
     */
    private Integer code;

    /**
     * 结果集
     */
    private T data;

    /**
     * 描述
     */
    private String message;

    public R(IErrorCode errorCode) {
        errorCode = Optional.ofNullable(errorCode).orElse(ErrorCodeEnum.FAILED);
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
    }

    public static <T> R<T> ok() {
        return restResult(null, ErrorCodeEnum.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ErrorCodeEnum.SUCCESS);
    }

    public static <T> R<T> failed() {
        return restResult(null, ErrorCodeEnum.FAILED);
    }

    public static <T> R<T> failed(String message) {
        return restResult(null, ErrorCodeEnum.FAILED.getCode(), message);
    }

    public static <T> R<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> R<T> failed(Integer code, String message) {
        return restResult(null, code, message);
    }

    public static <T> R<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMessage());
    }

    private static <T> R<T> restResult(T data, Integer code, String message) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(message);
        return apiResult;
    }

}
